package org.example.framework.protocol.http;

import cn.hutool.core.io.IoUtil;
import org.example.framework.Invocation;
import org.example.framework.register.LocalRegister;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author shenguangyang
 */
public class HttpServerHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp)  {
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            // 执行方法
            String interfaceName = invocation.getInterfaceName();
            String version = invocation.getVersion();
            Class<?> aClass = LocalRegister.get(interfaceName, version);
            Method method = aClass.getMethod(invocation.getMethodName(), invocation.getParamType());
            Object invoke = method.invoke(aClass.newInstance(), invocation.getParams());
            if (invoke instanceof Serializable) {
                IoUtil.writeUtf8(resp.getOutputStream(), true, invoke);
            }
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                 IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
